package linker.plugin;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import linker.account.ManageAccount;
import linker.window.WindowSaver;

/**
 * 
 * @version linker 0.93
 * @author Jianfeng jianfeng.linker@gmail.com
 * 
 */
public class PluginManager extends JFrame implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L; 

	private JTable table = new JTable();

	private DefaultTableModel tableModel = new DefaultTableModel();

	private JButton changeButton = new JButton("Change status");

	private static JButton sendButton = new JButton("Send");

	private static String currentJID = null;

	private static PluginManager pluginManager;

	private Vector<File> fileVector = new Vector<File>();

	public PluginManager() {
		super("Plugin Manager");

		String path = ManageAccount.getPath() + "plugins";
		File pluginDirectory = new File(path);

		Container container = getContentPane();
		container.setLayout(new BorderLayout());

		JPanel userPanel = new JPanel();
		changeButton.addActionListener(this);
		userPanel.add(changeButton);
		sendButton.addActionListener(this);
		sendButton.setEnabled(false);
		userPanel.add(sendButton);
		container.add(userPanel, BorderLayout.NORTH);

		tableModel.addColumn("Name");
		tableModel.addColumn("Used count");
		tableModel.addColumn("Status");
		table.setColumnSelectionAllowed(false);
		table.setCellSelectionEnabled(false);
		table.setRowSelectionAllowed(true);
		table.setModel(tableModel);
		container.add(new JScrollPane(table), BorderLayout.CENTER);

		if (pluginDirectory.isDirectory()) {
			File[] temp = pluginDirectory.listFiles();
			fileVector = new Vector<File>();
			for (int i = 0; i < temp.length; i++) {
				if (temp[i].isDirectory())
					fileVector.add(temp[i]);
			}

			for (int i = 0; i < fileVector.size(); i++) {
				Vector info = PluginInfo.getInfo(fileVector.elementAt(i));
				if (info != null)
					tableModel.addRow(info);
			}
		}

		setSize(300, 400);
		this.setLocationRelativeTo(null);
		setLocationRelativeTo(null);
		try {
			WindowSaver.getWindowSaver().loadSettings(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
		setVisible(true);
	} 

	public static void setJID(String JID) {
		getPluginManager();

		currentJID = JID;
		sendButton.setEnabled(true);
	}

	public static PluginManager getPluginManager() {
		if (pluginManager == null)
			pluginManager = new PluginManager();

		return pluginManager;
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == sendButton) {
			PluginShare.sendPlugin(currentJID, fileVector.elementAt(table
					.getSelectedRow()));
		}
	}
}
